package cn.cq.config;

import cn.dev33.satoken.stp.StpUtil;
import lombok.AllArgsConstructor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * cn.cq.config
 *
 * @author  dicraft
 */
@AllArgsConstructor
public class RequestInterceptor implements HandlerInterceptor {

    private String tokenName;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String tokenValue = request.getHeader(tokenName);
        if(ObjectUtils.isEmpty(tokenValue) && !exclude(request.getRequestURI())){
            throw new Exception("token缺失，请重新登录！");
        }else{
            String accountId =  (String) StpUtil.getLoginIdByToken(tokenValue);
            if(!exclude(request.getRequestURI()) && ObjectUtils.isEmpty(accountId)){
                throw new Exception("token已过期，请重新登录！");
            }
        }
        return true;
    }

    /**
     * 排除uri地址
     * @param uri
     * @return
     */
    private boolean exclude(String uri){
        return uri.contains("/doLogin")
                || uri.contains("/doLogout")
                || uri.contains("/preview")
                || uri.contains("Captcha")
                || uri.contains("/error")
                || uri.contains("/mobile")
                || uri.contains("/upload")
                ;
    }
}
